package com.chookss.home.gallery;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.GalleryListEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.gallery.adapter.GalleryListAdapter;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoNewCatesActivity;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.SelectDialogListener;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;

@SuppressLint("ValidFragment")
public class GalleryBaseFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.title_back)
    LinearLayout titleBack;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.ll_directory)
    LinearLayout llDirectory;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.llSearch)
    LinearLayout llSearch;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;

    private GalleryListAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private List<GalleryListEntity> list = new ArrayList<>();
    private View emptyView;
    private TextView tvEmpty,tvEmpty2;//空布局;
    private int type = 0; //0一级页面没有返回1是activity要返回
    private int roleType = 1; //roleType 0个人 1全部
    private int searchType = 1;// 1-日期 2-标签 3 地点
    private String catalogCodes = "";// 目录code
    private BottomListsDialog bottomListsDialog = null;
    private List<String> dialogList = new ArrayList<>();
    private List<KnowledgeEntity> videoFolderList = new ArrayList<>();//图库目录选择
    private int directorySOURSE = 5;//目录标识
    public GalleryBaseFragment() {

    }

    public GalleryBaseFragment(int type,int roleType) {
        this.type = type;
        this.roleType = roleType;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_gallery, container, false);
        unbinder = ButterKnife.bind(this, view);
        //注册接受
        EventBus.getDefault().register(this);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        //顶部状态栏 处理
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            LinearLayout.LayoutParams topAllParams = (LinearLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            statusBar.setVisibility(View.VISIBLE);
            statusBar.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            titleBack.setVisibility(View.INVISIBLE);
        } else {
            statusBar.setVisibility(View.GONE);
            titleBack.setVisibility(View.VISIBLE);
            if(roleType==0){
                common_title_txt.setText("我的图库");
                common_title_txt.setVisibility(View.VISIBLE);
                llSearch.setVisibility(View.GONE);
                llDirectory.setVisibility(View.GONE);
            }else{
                common_title_txt.setVisibility(View.GONE);
                llSearch.setVisibility(View.VISIBLE);
                llDirectory.setVisibility(View.VISIBLE);
            }
        }
        dialogList.add("日期");
        dialogList.add("标签");
        dialogList.add("地点");
        dialogList.add("取消");
        bottomListsDialog = new BottomListsDialog(mContext, dialogList, new SelectDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if(position<list.size()-1){
                    searchType=position+1;
                    smrRf.autoRefresh();
                    bottomListsDialog.setSelect(position);
                }
                bottomListsDialog.dismiss();
            }
        });
        bottomListsDialog.setSelect(0);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new GalleryListAdapter(R.layout.item_gallery_list, mContext, list, searchType+"",roleType);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setItemAnimator(null);
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvEmpty = emptyView.findViewById(R.id.tvEmpty);
        tvEmpty2 = emptyView.findViewById(R.id.tvEmpty2);
        if(roleType==1){
            tvEmpty.setText("暂无数据");
        }else{
            tvEmpty.setText("图库暂时还是空的");
            tvEmpty2.setText("块去发布你的第一张图片吧");
        }

        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        map.put("roleType", roleType+"");
        map.put("searchType", searchType + "");
        if(!Utils.isNull(catalogCodes)){
            map.put("catalogCodes", catalogCodes);
        }
        adapter.setType(searchType,searchType+"",catalogCodes,"","","");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<GalleryListEntity>>>() {
        }.getType(), null, Urls.selectAppImageList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<GalleryListEntity>>() {
            @Override
            public void onSuccess(List<GalleryListEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyDataSetChanged();
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    @OnClick({R.id.title_back, R.id.llSearch, R.id.ll_directory, R.id.ll_type})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.title_back:
                if (mContext != null) {
                    mContext.finish();
                }
                break;
            case R.id.llSearch:
                intent = new Intent(mContext, GallerySearchActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_directory:
                 intent = new Intent(mContext, VideoNewCatesActivity.class);
                Bundle bundle = new Bundle();
                //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
                ArrayList bundlelist = new ArrayList();
                bundlelist.add(videoFolderList);
                bundle.putParcelableArrayList("videoFolderList", bundlelist);
                intent.putExtras(bundle);
                intent.putExtra("videoType", directorySOURSE+"");
                startActivity(intent);
                break;
            case R.id.ll_type:
                if(bottomListsDialog!=null){
                    bottomListsDialog.show();
                }
                break;
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("videoCate"+directorySOURSE)) {
                //目录选择
                catalogCodes = map.get("videoCate"+directorySOURSE);
                videoFolderList.clear();
                videoFolderList.addAll(MyApp.videoFolderList);
                for (int i = 0; i <videoFolderList.size() ; i++) {

                }
                MyApp.videoFolderList.clear();
                smrRf.autoRefresh();
            }
        }
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("RefreshGallery".equals(msg)) {
                //刷新最近列表
                smrRf.autoRefresh();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        MyApp.videoFolderList.clear();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }


}
